<?php
  function get_secure_handler($auth) {
    return "https://prod-eagle.appspot.com/auth/?site=".
           $_SERVER["HTTP_HOST"]."&auth=$auth";
  }

  function auth() {
    if (isset($_POST["auth"])) {
      $auth = $_POST["auth"];
      $handle = @fopen(auth_file_path(), "r");
      $secret = false;
      if ($handle) {
        $secret = trim(fgets($handle, 4096));
      }
      if (ini_get("allow_url_fopen")) {
        if (!$secret or $secret != $auth) {
          $secret = false;
          $auth_url = get_secure_handler($auth);
          $handle = @fopen($auth_url, "r");
          if ($handle) {
            if (fgets($handle, 4096) == "OK") {
              $secret = $_POST["auth"];
              fwrite(fopen(auth_file_path(), "w+"), $secret);
            }
          }
        }
      } else if (!secret) {
        // If allow_url_fopen is not allowed, we just assume the first auth
        // request is from prodeagle.
        $secret = $_POST["auth"];
        fwrite(fopen(auth_file_path(), "w+"), $secret);
      }
      
      if ($auth == $secret) {
        return true;
      }
    }
    header('HTTP/1.0 401 Unauthorized');
    if (file_exists(auth_file_path())) {
      ?>
      <html>
        <body bgcolor="#AAAAAA" text="#333333">
          <center>
            <table style="border: 1px solid #333333; margin-top:10%;
                          background-color:#EEEEEE; padding: 50px;"><tr><td>
              <center>
                <h3>Authentication</h3>
                <form method=POST>
                  Please enter your ProdEagle secret which is stored here on your server:
                  <br/><br/><i><?php echo auth_file_path(); ?></i><br/><br/>
                  <input type=password name=auth><br/>
                  <input type=submit>
                </form>
              </center>
            </td></tr></table>
          </center>
        </body>
      </html>
      
      <?php
    } else {
      echo "ProdEagle hasn't set your secret yet. Please visit prodeagle.com ".
           "and register your website.";
    }
    return false;
  }

  function auth_file_path() {
    return dirname(__file__)."/data/.htprodeagle.auth";
  }
  
  function add_user() {
    if (isset($_GET["administrator"])) {
      header('Location: '.get_secure_handler($_POST["auth"]).
             "&administrator=".$_GET["administrator"]);
    } else {
      header('Location: '.get_secure_handler($_POST["auth"]).
             "&viewer=".$_GET["viewer"]);
    }
  }
  
?>